<?php
// +----------------------------------------------------------------------
// | xiongrui [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.xiongrui.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.xiongrui.cn>
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\controller\Admin;
use app\common\model\Fsend;
use Wechat\Loader;
use think\Request;

class Wechat extends Admin {
  protected $WxUser;
  public function _initialize() {
		parent::_initialize();
    $this->WxUser = model('WxUser');
	}

  public function index($keyword=null, $phone=null, $field=null, $order=null) {



    $map['nickname|name|phone'] = ['like', '%'.$keyword.'%'];
    $map['phone'] = ['like', '%'.$phone.'%'];

    if(getGroupId()==6){
      $map['rebate_code'] = session('user_auth.uid');
    }
    if($field){
      $ordermap = $field.' '.$order;
    }else{
      $ordermap = 'id desc';
    }

    $request = Request::instance();
    $param=$request->param();

    $list = $this->WxUser->where($map)->order($ordermap)->paginate(10,false,array('query' => $param));
    $count = $this->WxUser->where($map)->count();


		$this->assign('list', $list);
		$this->assign('count', $count);
		$this->setMeta('用户列表');
		return $this->fetch();



    // set_time_limit(0);
    // $user = & load_wechat('User');
    // $re = $this->WxUser->column('openid', 'id');
    // foreach ($re as $key => $value) {
    //
    //   $wxUser = $this->WxUser->get($key);
    //   if($wxUser){
    //     $result = $user->getUserInfo($value);
    //     $wxUser->subscribe = $result['subscribe'];
    //     $wxUser->nickname = $result['nickname'];
    //     $wxUser->sex = $result['sex'];
    //     $wxUser->city = $result['city'];
    //     $wxUser->province = $result['province'];
    //     $wxUser->country = $result['country'];
    //     $wxUser->headimgurl = $result['headimgurl'];
    //     $wxUser->subscribe_time = $result['subscribe_time'];
    //     $wxUser->remark = $result['remark'];
    //     $wxUser->groupid = $result['groupid'];
    //     $wxUser->save();
    //   }
    //
    // }



    // $user = & load_wechat('User');
    // $result = $user->getUserList($openid);
    // // 处理创建结果
    // if($result===FALSE){
    //     // 接口失败的处理
    //     echo $user->errMsg;
    // }else{
    //     $res = $result['data']['openid'];
    //
    //     if(is_array($res)){
    //       $userarr = array();
    //       foreach ($res as $key => $value) {
    //         $userarr[$key]['openid'] = $value;
    //       }
    //       if ($this->WxUser->saveAll($userarr)) {
    //               return '用户批量新增成功';
    //           } else {
    //               return $this->WxUser->getError();
    //       }
    //     }
    //
    // }
	}

  public function sendMessage($message){
    if (!$message) {
			return $this->error("请填写消息内容!");
		}
  	if (IS_POST) {
      set_time_limit(0);
      $infolist = $this->WxUser->where('subscribe',1)->select();

      foreach ($infolist as $key => $value) {

          $data = array();
          $data['touser'] = $value->openid;
          $data['msgtype'] = 'text';
          $data['text'] = array();
          $data['text']['content'] = $message;
          $wechat = &load_wechat('Receive');
          $result = $wechat->sendCustomMessage($data);
          if($result['errmsg']=="ok"){
              $fdata['user_ids'] .= $value->id.',';
          }

      }
      if($fdata['user_ids']){
        $fdata['message'] = $message;
        Fsend::create($fdata);
        $this->success('群发成功！');
      }else{
        $this->error('群发失败！');
      }

    }

  }

  /* 单字段编辑 */
	public function editable($name = null, $value = null, $pk = null) {
		if ($name && ($value != null || $value != '') && $pk) {
			db('WxUser')->where(array('id' => $pk))->setField($name, $value);
		}
	}

  public function getRebateUser(){
    $list = db('auth_group_access')->alias('a')->join('__MEMBER__ m ','m.uid= a.uid')->where(array('a.group_id' => 6))->column('a.uid,m.username');
    return json($list);
  }

  public function birthday($timen =null, $keyword = null){
    if($timen == 1){
      $data = date('md',time());
      $map['birthday_monthday'] = ['between', [(int)$data-100, (int)$data+100]];
    }else if ($timen == 2) {
      $data = date('md',time());
      $map['birthday_monthday'] = ['between', [(int)$data-200, (int)$data+200]];
    }
    $map['nickname|name|phone'] = ['like', '%'.$keyword.'%'];
    $map['birthday'] = ['neq', ''];
    $list = $this->WxUser->where($map)->order("member_time desc,send_birthday_coupon_time asc,date_format(birthday,'%m-%d') asc")->paginate(10);
		$this->assign('list', $list);
		$this->setMeta('用户列表');
		return $this->fetch();
  }
  public function sendcoupon($id){
    if (empty($id)) {
			return $this->error("非法操作！");
		}
    $date = date('Ymd',time());
    //生产一个10元优惠券
    $couponData =['coupon_id'=>4,'uid'=>$id,'code'=>date('md').rand_number(4),'total'=>'100','price'=>'10', 'coupon_dec'=>'生日优惠券'];
    $return = model('CouponList')->save($couponData);
    model('WxUser')->where('id', $id)->update(['send_birthday_coupon_time' => $date]);

    $userinfo = $this->WxUser->get($id);
    //发送给用户
    sendcomSms('SMS_69500018', ['name'=>$userinfo['name'], 'price'=>'10'], (string)$userinfo['phone']);
    //插入行为日志
    $data['action_id']   = 15; //行为id为 13  后台生成
    $data['user_id']     = $id;
    $data['action_ip']   = ip2long(get_client_ip());
    $data['create_time'] = time();
    $data['remark'] = time_format($data['create_time']).'送生日优惠券10元';
    db('ActionLog')->insert($data);


    if($return){
      return $this->success("操作成功");
    }else{
      return $this->error("操作失败");
    }
  }



  public function edit($id) {
		if (!$id) {
			return $this->error("非法操作！");
		}
		if (IS_POST) {
      $data['name'] = input('post.name');
      $data['phone'] = input('post.phone');
      $data['birthday'] = input('post.birthday');
      $data['birthday_monthday'] = input('post.birthday_monthday');

      //判断是否是第一次提交
      $info = model('wxUser')->where('id', $id)->find();
      //注册时间
      if(!$info['member_time']){
        $data['member_time'] = time();
      }
      model('wxUser')->where('id', $id)->update($data);
			return $this->success("编辑成功！", url('admin/wechat/birthday'));
		} else {
      $info = $this->WxUser->get($id);

			$this->assign('info', $info);
			$this->setMeta("编辑用户");
			return $this->fetch('');
		}
	}

  public function consume($id) {
		if (!$id) {
			return $this->error("非法操作！");
		}
		if (IS_POST) {
        $name = input('post.name');
        $phone = input('post.phone');
        $birthday = input('post.birthday');
        $birthday_monthday = input('post.birthday_monthday');
        $monetary = input('post.monetary');


        if(empty($name)){
          $this->error('用户名称必须填写');
        }
        if(empty($birthday)){
          $this->error('用户生日必须填写');
        }
        if(empty($monetary)){
          $this->error('请填写消费金额！');
        }
        if(!isMobile($phone)){
          $this->error('手机号码不存在或格式不对');
        }
        $info = $this->WxUser->get($id);

        if($monetary <= $info->balance){
          $beforeBalance = $info->balance;


          $yw = $info->balance-$monetary;//余额
          $integral = $info['integral']+ (int)$monetary;
          $this->WxUser->where('id', $id)->update(['balance'=>$yw,'name'=>$name,'phone'=>$phone, 'birthday'=>$birthday, 'birthday_monthday'=>$birthday_monthday, 'integral'=>$integral]);
          //发送给用户
          sendcomSms('SMS_67655286', ['user'=>$info['nickname'], 'time'=>date('Y-m-d H:i:s', time()), 'money'=>(string)$monetary, 'balance'=>(string)$yw, 'integral'=>(string)$integral], (string)$phone);
          //发送给管理元
          sendcomSms('SMS_68145090', ['user'=>$info['nickname'], 'time'=>date('Y-m-d H:i:s', time()), 'money'=>(string)$monetary, 'order'=>'后台消费'], '15885108322');
          sendcomSms('SMS_68145090', ['user'=>$info['nickname'], 'time'=>date('Y-m-d H:i:s', time()), 'money'=>(string)$monetary, 'order'=>'后台消费'], '13638516023');

          //插入行为日志
          $data['action_id']   = 16; //行为id为 13  后台生成
          $data['user_id']     = $id;
          $data['action_ip']   = ip2long(get_client_ip());
          $data['create_time'] = time();
          $data['remark'] = time_format($data['create_time']).'后台消费'.$monetary.'元';
          db('ActionLog')->insert($data);

          //消费记录
          $dataTcord['user_id'] =  $id;
          $dataTcord['sum'] =  $monetary;
          $dataTcord['status'] =  1;
          $dataTcord['create_time'] =  time();
          $dataTcord['before_balance'] =  $beforeBalance;
          $dataTcord['after_balance'] =  $yw;
          $dataTcord['description'] =  '后台消费';
          $dataTcord['admin_id'] =  session('user_auth.uid');
          db('consumeLog')->insert($dataTcord);


          return $this->success("提交成功！");

        }else{
          $this->error('余额不足');
        }


		} else {
      $info = $this->WxUser->get($id);

			$this->assign('info', $info);
			$this->setMeta("消费");
			return $this->fetch('');
		}
	}
  public function topup($id) {
		if (!$id) {
			return $this->error("非法操作！");
		}
		if (IS_POST) {
      $name = input('post.name');
      $phone = input('post.phone');
      $birthday = input('post.birthday');
      $birthday_monthday = input('post.birthday_monthday');
      $monetary = input('post.monetary');


      if(empty($name)){
        $this->error('用户名称必须填写');
      }
      if(empty($birthday)){
        $this->error('用户生日必须填写');
      }
      if(empty($monetary)){
        $this->error('请填写充值金额！');
      }
      if(!isMobile($phone)){
        $this->error('手机号码不存在或格式不对');
      }
        $info = $this->WxUser->get($id);

        if($monetary >= 0){
          $beforeBalance =  $info['balance'];

          $this->WxUser->where('id', $id)->setInc('balance', $monetary);
          $this->WxUser->where('id', $id)->update(['name'=>$name,'phone'=>$phone, 'birthday'=>$birthday, 'birthday_monthday'=>$birthday_monthday]);
          //会员充值
          $yw = $monetary + $info->balance;
          sendcomSms('SMS_67595309', ['user'=>$info['nickname'], 'time'=>date('Y-m-d H:i:s', time()), 'topup'=>(string)$monetary, 'balance'=>(string)$yw, 'integral'=>(string)$info['integral']], (string)$phone);

          sendcomSms('SMS_68070113', ['user'=>$info['name'].'，微信名'.$info['nickname'].'。', 'topup'=>(string)$monetary, 'balance'=>(string)$yw, 'integral'=>(string)$info['integral']], '15885108322');
          sendcomSms('SMS_68070113', ['user'=>$info['name'].'，微信名'.$info['nickname'].'。', 'topup'=>(string)$monetary, 'balance'=>(string)$yw, 'integral'=>(string)$info['integral']], '13638516023');

          //插入行为日志
          $data['action_id']   = 17; //行为id为 13  后台生成
          $data['user_id']     = $id;
          $data['action_ip']   = ip2long(get_client_ip());
          $data['create_time'] = time();
          $data['remark'] = time_format($data['create_time']).'后台充值'.$monetary.'元';
          db('ActionLog')->insert($data);

          //充值记录
          $dataTcord['user_id'] =  $id;
          $dataTcord['sum'] =  $monetary;
          $dataTcord['status'] =  1;
          $dataTcord['create_time'] =  time();
          $dataTcord['before_balance'] =  $beforeBalance;
          $dataTcord['after_balance'] =  $yw;
          $dataTcord['description'] =  '后台充值';
          $dataTcord['admin_id'] =  session('user_auth.uid');
          db('topupLog')->insert($dataTcord);

          return $this->success("充值成功！");

        }else{
          $this->error('充值金额不正确');
        }


		} else {
      $info = $this->WxUser->get($id);

			$this->assign('info', $info);
			$this->setMeta("充值");
			return $this->fetch('');
		}
	}


  public function toogleBlacklist($id, $value = 1) {
		$result = $this->WxUser->where(array('id' => $id))->setField(array('is_blacklist' => $value));
		if ($result !== false) {
			return $this->success('操作成功！');
		} else {
			return $this->error('操作失败！');
		}
	}
  //核对微信是否付款
  public function wechatIsPay($out_trade_no){
    $pay = & load_wechat('Pay');
    $orderStatus = $pay->queryOrder($out_trade_no);

    if($orderStatus['trade_state'] == 'SUCCESS'){
      $this->success('核对成功','',$orderStatus);
    }else {
      $this->success('核对失败');
    }
  }

  /**
   * 充值记录
   */
  public function topupRcord(){
    $keyword = input('keyword');
    if($keyword){
      $map['nickname|name|phone'] = ['like', '%'.$keyword.'%'];
      $uid = model('WxUser')->where($map)->column('id');
    }

    $m['status'] = 1;
    if($uid){
      $m['user_id'] = ['in', $uid];
    }
    if(session('user_auth.uid') != 1){
      $m['admin_id'] = session('user_auth.uid');
    }


    $list = model('topupLog')->where($m)->order('id desc')->paginate(10);
    $this->assign('list', $list);
    $this->setMeta("充值记录");
    return $this->fetch();
  }

  /**
   * 消费记录
   */
   public function consumeRecord(){
     $keyword = input('keyword');
     if($keyword){
       $map['nickname|name|phone'] = ['like', '%'.$keyword.'%'];
       $uid = model('WxUser')->where($map)->column('id');
     }

     $m['status'] = 1;
     if($uid){
       $m['user_id'] = ['in', $uid];
     }
     if(session('user_auth.uid') != 1){
       $m['admin_id'] = session('user_auth.uid');
     }
     $list = model('consumeLog')->where($m)->order('id desc')->paginate(10);
     $this->assign('list', $list);
     $this->setMeta("消费记录");
     return $this->fetch();
   }

   /**
    * 优惠券使用记录
    */
    public function couponRecord(){
      $keyword = input('keyword');
      if($keyword){
        $map['nickname|name|phone'] = ['like', '%'.$keyword.'%'];
        $uid = model('WxUser')->where($map)->column('id');
      }

      $m['status'] = 1;
      if($uid){
        $m['uid'] = ['in', $uid];
      }

      $list = model('couponList')->where($m)->order('use_time desc')->paginate(10);
      $this->assign('list', $list);
      $this->setMeta("优惠券使用记录");
      return $this->fetch();
    }

}

 ?>
